package com.boot.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boot.constants.RedisKeys;
import com.boot.constants.StatusConstants;
import com.boot.entity.Question;
import com.boot.entity.QuestionAssignment;
import com.boot.entity.User;
import com.boot.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class ResolvedNotificationTask {

    @Resource
    private IQuestionService questionService;

    @Resource
    private IQuestionAssignmentService questionAssignmentService;

    @Resource
    private IUserService userService;

    @Resource
    private MailService mailService;

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    /**
     * 每隔 2 分钟执行一次
     */
    @Scheduled(fixedDelay = 2_000)
    public void scanAndNotifyPendingReviews() {
        log.info("[定时任务] 开始扫描已解决的问题...");

        try {
            handleResolvedQuestions();
        } catch (Exception e) {
            log.error("【通知任务异常】" + e.getMessage(), e);
        }
    }

    /**
     * 扫描所有状态为 resolved 但未通知的问题，向处理该问题的专家发送提醒
     */
    private void handleResolvedQuestions() {
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        wrapper.eq("status", StatusConstants.QuestionStatus.RESOLVED)
               .isNotNull("id");

        List<Question> resolvedQuestions = questionService.list(wrapper);
        log.info("找到 {} 个已解决的问题待通知", resolvedQuestions.size());

        for (Question q : resolvedQuestions) {
            String idKey = String.valueOf(q.getId());

            // 检查是否已通知
            Boolean hasNotified = redisTemplate.opsForSet().isMember(RedisKeys.SENT_RESOLVED_NOTIFY, idKey);
            if (Boolean.TRUE.equals(hasNotified)) {
                continue;
            }

            try {
                // 获取已接受该问题的专家
                QuestionAssignment assignment = questionAssignmentService.getOne(
                        new QueryWrapper<QuestionAssignment>()
                                .eq("question_id", q.getId())
                                .eq("accepted", StatusConstants.AssignmentStatus.ACCEPTED)
                                .last("LIMIT 1")
                );

                if (assignment == null) {
                    log.warn("问题ID={} 被标记为已解决，但未找到已接受的专家", q.getId());
                    redisTemplate.opsForSet().add(RedisKeys.SENT_RESOLVED_NOTIFY, idKey);
                    continue;
                }

                User expert = userService.getById(assignment.getExpertId());
                if (expert == null || expert.getEmail() == null || expert.getEmail().trim().isEmpty()) {
                    log.warn("专家ID={} 无邮箱，无法发送通知", assignment.getExpertId());
                    redisTemplate.opsForSet().add(RedisKeys.SENT_RESOLVED_NOTIFY, idKey);
                    continue;
                }

                String subject = "🎉 您解答的问题已解决：" + truncate(q.getTitle(), 50);
                String content = buildQuestionResolvedToExpertEmail(expert.getUsername(), q.getTitle());

                mailService.sendHtmlMail(expert.getEmail(), subject, content);
                log.info("✅ 已发送“问题已解决”通知给专家 {} (邮箱: {}), 问题ID={}", expert.getUsername(), expert.getEmail(), q.getId());

                // 标记为已通知
                redisTemplate.opsForSet().add(RedisKeys.SENT_RESOLVED_NOTIFY, idKey);

            } catch (Exception e) {
                log.error("📧 发送“问题已解决”通知失败（问题ID=" + q.getId() + "）：" + e.getMessage(), e);
            }
        }
    }

    // ==================== 邮件内容构建 ====================

    /**
     * 构建：问题已解决后，通知回答专家
     */
    public String buildQuestionResolvedToExpertEmail(String expertName, String questionTitle) {
        return "<div style='font-family: Arial, sans-serif; padding: 20px; border: 1px solid #ddd; border-radius: 8px; max-width: 600px; margin: auto;'>"
                    + "<h2 style='color: #4CAF50;'>🎉 您解答的问题已成功解决</h2>"
                    + "<p><strong>您好，" + escapeHtml(expertName) + "：</strong></p>"
                    + "<p>您参与解答的问题 <em>“" + escapeHtml(questionTitle) + "”</em> 已被标记为 <strong>“已解决”</strong>。</p>"
                    + "<p>感谢您的专业贡献！您的帮助让社区更有价值。</p>"
                    + "<p>如需查看完整对话记录，请登录系统查看详情。</p>"
                    + "<footer style='margin-top: 30px; color: #777; font-size: 0.9em; text-align: center;'>"
                    + "&copy; " + java.time.LocalDate.now().getYear() + " 系统管理平台</footer>"
                + "</div>";
    }

    // ==================== 工具方法 ====================

    private String escapeHtml(String str) {
        if (str == null) return "";
        return str.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#x27;");
    }

    private String truncate(String str, int len) {
        if (str == null) return "";
        return str.length() <= len ? str : str.substring(0, len) + "...";
    }
}
